package net.zjitc.list.web;

import net.zjitc.list.dao.UserDao;
import net.zjitc.list.dao.UserDaoImpl;
import net.zjitc.list.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2020/6/18 14:52
 * 修改用户Servlet
 **/
@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 0、设置请求编码
           1、接受请求参数
           2、将所有请求参数封装成user对象
           3、调用dao层完成数据更新功能
           4、重定向到userListServlet
        * */
        /* 获取所有请求参数：Jsp页面name值作为map的key值
        *                         value作为map的value*/
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user=new User();
        try {
            /* 通过BeanUtils将map数据封装成user对象*/
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        /* 调用dao层的方法完成更新功能*/
        UserDao dao=new UserDaoImpl();
        dao.update(user);
        /* 重定向:要加项目路径*/
        response.sendRedirect(request.getContextPath()+"/userListServlet");

    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
